<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据推送 - DTU管理系统</title>
    <script src="js/toast.js"></script>
    <link rel="stylesheet" href="css/common.css">
    <style>
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .protocol-config {
            display: none;
        }
        
        .protocol-config.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>数据推送</h1>
        <div class="breadcrumb">DTU管理系统 / 数据推送</div>
    </div>

    <div class="container">
        <!-- Tab导航 -->
        <div class="nav-tabs">
            <a href="index.html" class="nav-tab">首页</a>
            <a href="network.html" class="nav-tab">网络配置</a>
            <a href="serial.html" class="nav-tab">串口配置</a>
            <a href="collect.html" class="nav-tab">数据采集</a>
            <a href="push.html" class="nav-tab active">数据推送</a>
            <a href="at-command.html" class="nav-tab">AT命令</a>
            <a href="system.html" class="nav-tab">系统设置</a>
        </div>
        
        <!-- 推送协议选择 -->
        <div class="config-section">
            <h3>推送协议选择</h3>
                <div class="form-group">
                    <label for="push-protocol">推送协议</label>
                    <select id="push-protocol" onchange="changePushProtocol()">
                        <option value="0" selected>MQTT</option>
                        <option value="1">HTTP</option>
                        <option value="2">TCP</option>
                        <option value="3">UDP</option>
                    </select>
                </div>
        </div>

        <!-- MQTT配置 -->
        <div class="config-section protocol-config active" id="mqtt-config">
            <h3>MQTT配置</h3>
            <form id="mqtt-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="mqtt-host">服务器地址</label>
                        <input type="text" id="mqtt-host" value="mqtt.example.com" placeholder="例如: mqtt.example.com">
                    </div>
                    <div class="form-group">
                        <label for="mqtt-port">端口</label>
                        <input type="number" id="mqtt-port" value="1883" min="1" max="65535">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="mqtt-username">用户名</label>
                        <input type="text" id="mqtt-username" placeholder="可选">
                    </div>
                    <div class="form-group">
                        <label for="mqtt-password">密码</label>
                        <input type="password" id="mqtt-password" placeholder="可选">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="mqtt-client-id">客户端ID</label>
                        <input type="text" id="mqtt-client-id" value="DTU001" placeholder="例如: DTU001">
                    </div>
                    <div class="form-group">
                        <label for="mqtt-topic">主题</label>
                        <input type="text" id="mqtt-topic" value="dtu/data" placeholder="例如: dtu/data">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="mqtt-keepalive">保活时间(秒)</label>
                        <input type="number" id="mqtt-keepalive" value="60" min="10" max="3600">
                    </div>
                    <div class="form-group">
                        <label for="mqtt-qos">QoS等级</label>
                        <select id="mqtt-qos">
                            <option value="0" selected>0 - 最多一次</option>
                            <option value="1">1 - 至少一次</option>
                            <option value="2">2 - 仅一次</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="mqtt-ssl">
                            <label for="mqtt-ssl">启用SSL/TLS加密</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="mqtt-clean-session" checked>
                            <label for="mqtt-clean-session">清除会话</label>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- HTTP配置 -->
        <div class="config-section protocol-config" id="http-config">
            <h3>HTTP配置</h3>
            <form id="http-form">
                <div class="form-group">
                    <label for="http-url">服务器URL</label>
                    <input type="text" id="http-url" value="http://example.com/api/data" placeholder="http://example.com/api/data">
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="http-method">请求方法</label>
                        <select id="http-method">
                            <option value="POST" selected>POST</option>
                            <option value="PUT">PUT</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="http-content-type">内容类型</label>
                        <select id="http-content-type">
                            <option value="application/json" selected>application/json</option>
                            <option value="application/x-www-form-urlencoded">application/x-www-form-urlencoded</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="http-username">用户名</label>
                        <input type="text" id="http-username" placeholder="可选">
                    </div>
                    <div class="form-group">
                        <label for="http-password">密码</label>
                        <input type="password" id="http-password" placeholder="可选">
                    </div>
                </div>
                <div class="form-group">
                    <label for="http-headers">自定义头部</label>
                    <textarea id="http-headers" rows="3" placeholder="Authorization: Bearer token&#10;X-API-Key: your-key"></textarea>
                </div>
            </form>
        </div>

        <!-- TCP配置 -->
        <div class="config-section protocol-config" id="tcp-config">
            <h3>TCP配置</h3>
            <form id="tcp-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="tcp-host">服务器地址</label>
                        <input type="text" id="tcp-host" value="192.168.1.100" placeholder="例如: 192.168.1.100">
                    </div>
                    <div class="form-group">
                        <label for="tcp-port">端口</label>
                        <input type="number" id="tcp-port" value="8080" min="1" max="65535">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="tcp-format">数据格式</label>
                        <select id="tcp-format">
                            <option value="json" selected>JSON</option>
                            <option value="binary">二进制</option>
                            <option value="text">文本</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="tcp-keepalive" checked>
                            <label for="tcp-keepalive">保持连接</label>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- UDP配置 -->
        <div class="config-section protocol-config" id="udp-config">
            <h3>UDP配置</h3>
            <form id="udp-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="udp-host">服务器地址</label>
                        <input type="text" id="udp-host" value="192.168.1.100" placeholder="例如: 192.168.1.100">
                    </div>
                    <div class="form-group">
                        <label for="udp-port">端口</label>
                        <input type="number" id="udp-port" value="8080" min="1" max="65535">
                    </div>
                </div>
                <div class="form-group">
                    <label for="udp-format">数据格式</label>
                    <select id="udp-format">
                        <option value="json" selected>JSON</option>
                        <option value="binary">二进制</option>
                        <option value="text">文本</option>
                    </select>
                </div>
            </form>
        </div>

        <!-- 通用配置 -->
        <div class="config-section">
            <h3>通用配置</h3>
            <form id="push-common-form">
                <div class="form-row">
                    <div class="form-group">
                        <label for="push-timeout">超时时间(秒)</label>
                        <input type="number" id="push-timeout" value="30" min="5" max="300">
                    </div>
                    <div class="form-group">
                        <label for="push-retry-count">重试次数</label>
                        <input type="number" id="push-retry-count" value="3" min="0" max="10">
                    </div>
                    <div class="form-group">
                        <label for="push-retry-interval">重试间隔(秒)</label>
                        <input type="number" id="push-retry-interval" value="5" min="1" max="60">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label for="push-data-format">数据格式</label>
                        <select id="push-data-format">
                            <option value="0" selected>JSON</option>
                            <option value="1">XML</option>
                            <option value="2">CSV</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="push-compression">
                            <label for="push-compression">启用数据压缩</label>
                        </div>
                    </div>
                </div>
                <button type="button" class="btn btn-primary" onclick="savePushConfig()">保存配置</button>
                <button type="button" class="btn btn-secondary" onclick="testPushConnection()">测试连接</button>
                <button type="button" class="btn btn-success" onclick="testPushData()">测试推送</button>
            </form>
        </div>
    </div>

    <!-- Toast容器 -->
    <div class="toast-container" id="toast-container"></div>

    <script>
        // API请求封装
        async function apiRequest(url, method = 'GET', data = null) {
            try {
                const options = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };

                if (data) {
                    options.body = JSON.stringify(data);
                }

                const response = await fetch(url, options);
                const result = await response.json();

                if (!response.ok) {
                    throw new Error(result.error?.message || '请求失败');
                }

                return result;
            } catch (error) {
                console.error('API请求错误:', error);
                showMessage(error.message, 'danger');
                throw error;
            }
        }

        // 数据推送相关函数
        function changePushProtocol() {
            const protocol = document.getElementById('push-protocol').value;

            // 隐藏所有协议配置
            document.querySelectorAll('.protocol-config').forEach(config => {
                config.classList.remove('active');
            });

            // 显示选中的协议配置
            switch(protocol) {
                case '0': // MQTT
                    document.getElementById('mqtt-config').classList.add('active');
                    break;
                case '1': // HTTP
                    document.getElementById('http-config').classList.add('active');
                    break;
                case '2': // TCP
                    document.getElementById('tcp-config').classList.add('active');
                    break;
                case '3': // UDP
                    document.getElementById('udp-config').classList.add('active');
                    break;
            }
        }

        async function savePushConfig() {
            const protocol = parseInt(document.getElementById('push-protocol').value);
            let data = {
                protocol: protocol,
                format: parseInt(document.getElementById('push-data-format').value),
                timeout: parseInt(document.getElementById('push-timeout').value),
                retry_count: parseInt(document.getElementById('push-retry-count').value),
                retry_interval: parseInt(document.getElementById('push-retry-interval').value),
                enable_compression: document.getElementById('push-compression').checked
            };

            // 根据协议类型添加特定配置
            switch(protocol) {
                case 0: // MQTT
                    data.server_host = document.getElementById('mqtt-host').value;
                    data.server_port = parseInt(document.getElementById('mqtt-port').value);
                    data.username = document.getElementById('mqtt-username').value;
                    data.password = document.getElementById('mqtt-password').value;
                    data.topic = document.getElementById('mqtt-topic').value;
                    data.client_id = document.getElementById('mqtt-client-id').value;
                    data.keepalive = parseInt(document.getElementById('mqtt-keepalive').value);
                    data.qos = parseInt(document.getElementById('mqtt-qos').value);
                    data.enable_ssl = document.getElementById('mqtt-ssl').checked;
                    data.clean_session = document.getElementById('mqtt-clean-session').checked;
                    break;
                case 1: // HTTP
                    data.server_host = document.getElementById('http-url').value;
                    data.method = document.getElementById('http-method').value;
                    data.content_type = document.getElementById('http-content-type').value;
                    data.username = document.getElementById('http-username').value;
                    data.password = document.getElementById('http-password').value;
                    data.headers = document.getElementById('http-headers').value;
                    break;
                case 2: // TCP
                    data.server_host = document.getElementById('tcp-host').value;
                    data.server_port = parseInt(document.getElementById('tcp-port').value);
                    data.data_format = document.getElementById('tcp-format').value;
                    data.keepalive = document.getElementById('tcp-keepalive').checked;
                    break;
                case 3: // UDP
                    data.server_host = document.getElementById('udp-host').value;
                    data.server_port = parseInt(document.getElementById('udp-port').value);
                    data.data_format = document.getElementById('udp-format').value;
                    break;
            }

            try {
                await apiRequest('/api/push', 'POST', data);
                showMessage('推送配置保存成功');
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }

        async function testPushConnection() {
            try {
                showMessage('正在测试推送连接...', 'info');
                const result = await apiRequest('/api/push/test-connection', 'POST');
                
                if (result.success) {
                    showMessage('推送连接测试成功');
                } else {
                    showMessage('推送连接测试失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('测试失败: ' + error.message, 'danger');
            }
        }

        async function testPushData() {
            try {
                showMessage('正在测试数据推送...', 'info');
                const result = await apiRequest('/api/push/test-data', 'POST');
                
                if (result.success) {
                    showMessage('数据推送测试成功');
                } else {
                    showMessage('数据推送测试失败: ' + result.error, 'danger');
                }
            } catch (error) {
                showMessage('测试失败: ' + error.message, 'danger');
            }
        }

        // 加载推送配置
        async function loadPushConfig() {
            try {
                const config = await apiRequest('/api/push');
                updatePushDisplay(config);
            } catch (error) {
                console.error('加载推送配置失败:', error);
            }
        }

        function updatePushDisplay(config) {
            document.getElementById('push-protocol').value = config.protocol || 0;
            document.getElementById('push-data-format').value = config.format || 0;
            document.getElementById('push-timeout').value = config.timeout || 30;
            document.getElementById('push-retry-count').value = config.retry_count || 3;
            document.getElementById('push-retry-interval').value = config.retry_interval || 5;
            document.getElementById('push-compression').checked = config.enable_compression || false;

            // 更新协议特定配置
            if (config.protocol === 0) { // MQTT
                document.getElementById('mqtt-host').value = config.server_host || '';
                document.getElementById('mqtt-port').value = config.server_port || 1883;
                document.getElementById('mqtt-username').value = config.username || '';
                document.getElementById('mqtt-password').value = config.password || '';
                document.getElementById('mqtt-topic').value = config.topic || '';
                document.getElementById('mqtt-client-id').value = config.client_id || '';
                document.getElementById('mqtt-keepalive').value = config.keepalive || 60;
                document.getElementById('mqtt-qos').value = config.qos || 0;
                document.getElementById('mqtt-ssl').checked = config.enable_ssl || false;
                document.getElementById('mqtt-clean-session').checked = config.clean_session !== false;
            } else if (config.protocol === 1) { // HTTP
                document.getElementById('http-url').value = config.server_host || '';
                document.getElementById('http-method').value = config.method || 'POST';
                document.getElementById('http-content-type').value = config.content_type || 'application/json';
                document.getElementById('http-username').value = config.username || '';
                document.getElementById('http-password').value = config.password || '';
                document.getElementById('http-headers').value = config.headers || '';
            } else if (config.protocol === 2) { // TCP
                document.getElementById('tcp-host').value = config.server_host || '';
                document.getElementById('tcp-port').value = config.server_port || 8080;
                document.getElementById('tcp-format').value = config.data_format || 'json';
                document.getElementById('tcp-keepalive').checked = config.keepalive !== false;
            } else if (config.protocol === 3) { // UDP
                document.getElementById('udp-host').value = config.server_host || '';
                document.getElementById('udp-port').value = config.server_port || 8080;
                document.getElementById('udp-format').value = config.data_format || 'json';
            }

            // 切换到正确的协议配置
            changePushProtocol();
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('数据推送页面已加载');
            
            // 加载推送配置
            loadPushConfig();
            
            // 设置推送协议切换
            changePushProtocol();
        });
    </script>
</body>
</html>